<script setup lang="ts">
import { useRouter, useRoute, } from 'vue-router'
import { ref, onMounted, watch } from 'vue'

const router = useRouter()
const route = useRoute()
const isLoggedIn = ref(false)

// 检查登录状态的函数
const checkLoginStatus = () => {
  const loginStatus = sessionStorage.getItem('isLoggedIn') === 'true'
  console.log('当前登录状态:', loginStatus ? '已登录' : '未登录')
  isLoggedIn.value = loginStatus
}

// 组件挂载时检查登录状态
onMounted(() => {
  console.log('底部导航组件已加载')
  checkLoginStatus()
})

// 监听路由变化，每次路由变化时重新检查登录状态
watch(() => route.path, (newPath) => {
  console.log('路由变化:', newPath)
  checkLoginStatus()
})

// 定义导航方法，类型安全地跳转到指定路径
const navigate = (path: string): void => {
  if (!isLoggedIn.value) {
    console.log('用户未登录，正在重定向到登录页面')
    router.push('/login')
    return
  }
  console.log('导航到:', path)
  router.push(path)
}

// 定义 isActive 方法，并明确返回值类型为 boolean
const isActive = (path: string): boolean => {
  return route.path === path
}
</script>

<template>
  <nav v-if="isLoggedIn" class="bottom-nav">
    <div
      class="nav-item"
      :class="{ active: isActive('/') }"
      @click="navigate('/')"
    >
      <i class="nav-icon home">🏠</i>
      <span>首页</span>
    </div>
    <div
      class="nav-item"
      :class="{ active: isActive('/order') }"
      @click="navigate('/order')"
    >
      <i class="nav-icon order">🍽️</i>
      <span>点餐</span>
    </div>
    <div
      class="nav-item"
      :class="{ active: isActive('/delivery') }"
      @click="navigate('/delivery')"
    >
      <i class="nav-icon delivery">🛵</i>
      <span>订单</span>
    </div>
    <div
      class="nav-item"
      :class="{ active: isActive('/profile') }"
      @click="navigate('/profile')"
    >
      <i class="nav-icon profile">👤</i>
      <span>我的</span>
    </div>
  </nav>
</template>

<style scoped>
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 64px;
  background-color: #ffffff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  max-width: 430px;
  margin: 0 auto;
  /* 添加安全区域padding */
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 100%;
  color: #999;
  font-size: 12px;
  transition: all 0.3s ease;
  -webkit-tap-highlight-color: transparent;
}

.nav-item.active {
  color: #42b883;
}

.nav-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

@supports (-webkit-touch-callout: none) {
  .bottom-nav {
    /* iOS特定的安全区域padding */
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>